﻿using Dotnet.TopApi;
using Dotnet.TopApi.Request;
using HtmlAgilityPack;
using ScrapySharp.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Dotnet.Sui
{
    //GET https://www.sui.com/account/account.do HTTP/1.1
    public class DoAccountRequest : SuiRequest, ITopRequest<DoAccountResponse>
    {
        public string GetApiName()
        {
            return "account/account.do";
        }

        public IDictionary<string, string> GetParameters()
        {
            TopDictionary dict = base.GetParameters1() as TopDictionary;
            dict.AddHeadersMethod("GET");
            return dict;
        }

        public void Validate()
        {
           // throw new NotImplementedException();
        }
    }

    public class DoAccountResponse : SuiDoResponse
    {
        public override void ParseCateAccount(string html)
        {
            _cateAccount = Account(html);
        }
        private List<Account> Account(string html)
        {
            List<Account> accountList = new List<Account>();
            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var docNode = doc.DocumentNode;
            var firstZhNodes = docNode.CssSelect("div#l-list>div.l-list-in>a").ToList();

            List<Account> secAccountList = GetSecondAccount(html);
            for (int i = 0; i < firstZhNodes.Count; i++)
            {
                string id = (i + 1).ToString();
                string zh = firstZhNodes[i].CssSelect("span.ll-name").First().InnerText;
                string je = firstZhNodes[i].CssSelect("span.ll-money").First().InnerText;
                List<Account> list = secAccountList.Where(a => a.Name.StartsWith(id)).ToList();
                accountList.Add(new Account() { Id = id, Name = zh, ChildAccount = list });
            }
            return accountList;
        }
        private List<Account> GetSecondAccount(string html)
        {
            List<Account> accountList = new List<Account>();
            string scriptWindowParam = GetScriptWindowParam(html);

            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var docNode = doc.DocumentNode;
            var secondNodes = docNode.CssSelect("div#r-list>div.acc").ToList();

            foreach (var secondZh in secondNodes)
            {
                var zhName = secondZh.CssSelect("div.acc-info>div>div>div>table").First().CssSelect("a.edit").First().InnerText.Trim('"');
                string regEx = $"\"\\d+\":\"{zhName}\"";
                Regex reg = new Regex(regEx);
                string[] temp = reg.Match(scriptWindowParam).Value.Split(':');
                string zhId = (temp.Length >= 1 ? temp[0] : "").Trim('"');
                List<Account> thirdAccounts = GetThirdAccount(scriptWindowParam, zhName);
                accountList.Add(new Account() { Id = zhId, Name = zhName, ChildAccount = thirdAccounts });
            }
            return accountList.Count == 0 ? null : accountList;
        }
        private List<Account> GetThirdAccount(string scriptWindowParam, string parentName)
        {
            string id = parentName.Substring(0, 2);
            string regEx = $"\"\\d+\":\"{id}\\d+\\w+\"";
            Regex reg = new Regex(regEx);
            List<Account> list = new List<Account>();
            foreach (Match match in reg.Matches(scriptWindowParam))
            {
                string[] temp = match.Value.Split(':');
                string zhId = (temp.Length >= 1 ? temp[0] : "").Trim('"');
                string zhName = (temp.Length >= 2 ? temp[1] : "").Trim('"');
                list.Add(new Account() { Id = zhId, Name = zhName, ChildAccount = null });
            }
            return list.Count == 0 ? null : list;
        }
        private string GetScriptWindowParam(string html)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var docNode = doc.DocumentNode;
            var scriptNodes = docNode.CssSelect("script");
            foreach (var node in scriptNodes)
            {
                if (node.InnerText.Contains("window.$param"))
                {
                    return node.InnerText.Replace("window.$param", "").Replace("=", "").Trim();
                }
            }
            return "";
        }
    }
}
